import os, sys, re, time, shutil
from xml_snippet import HEAD, BODY, TAIL

# 存放自动切换文件的目录（Ubuntu默认）
XML_DIR = "/usr/share/backgrounds/contest"
# 存放壁纸图片的路径------->改成你自己存放壁纸的路径
IMAGE_DIR = "/usr/share/backgrounds/pictures"
# 每张壁纸展示的时间--------->改成你希望的每张壁纸的展示时间
DURATION_STATIC = 1600.0
# 图片之间切换的时间--------->同样可以修改
DURATION_TRANSITION = 5.0

class WallpaperSwitcher(object):
    """Ubuntu Desktop自动切换桌面壁纸
    """
    def __init__(self):
        self.xml_names = os.listdir(XML_DIR)
        self.img_dir = IMAGE_DIR
        self.head = HEAD
        self.body = BODY
        self.tail = TAIL
        self.duration_static = DURATION_STATIC
        self.duration_transition = DURATION_TRANSITION
    
    def get_xml_name(self):
        for xml in self.xml_names:
            if re.match(r'\w+\.xml$', xml):
                xml_name = xml
        return xml_name
    
    def get_img_names(self):
        img_names = os.listdir(self.img_dir)
        return img_names
    
    def generate_xml(self, xml_name, img_names):
        with open(xml_name, 'w') as f:
            index = 1
            for img_name in img_names:
                img_dir = self.img_dir + "/" + img_name
                if index == 1:
                    content = self.head.format(self.duration_static, img_dir, self.duration_transition, img_dir)
                elif index == len(img_names):
                    content = self.tail.format(img_dir, self.duration_static, img_dir)
                else:
                    content = self.body.format(img_dir, self.duration_static, img_dir, self.duration_transition, img_dir)
                f.write(content)
                index += 1
    
    def rename_old_xml(self, old_name, new_name):
        os.rename(XML_DIR + "/" + old_name, XML_DIR + "/" + new_name)

    def move_xml_to_dir(self, xml_name):
        shutil.move("./" + xml_name, XML_DIR + "/")
    
    def run(self):
        # 获取默认目录下的文件名
        xml_name = self.get_xml_name()
        # 获取指定的壁纸文件夹下的图片名列表
        img_names = self.get_img_names()
        # 在当前文件夹下生成新的xml文件， 文件名与旧xml文件同名
        self.generate_xml(xml_name, img_names)
        xml_name_new = xml_name + "_" + time.strftime("%Y%m%d")
        # 获取root权限
        if os.geteuid():
            args = [sys.executable] + sys.argv
            os.execlp('sudo', 'sudo', *args)
            print("Root: euid is", os.geteuid())
        # 将原有的xml文件重命名
        self.rename_old_xml(xml_name, xml_name_new)
        # 将生成的新xml文件移动到ubuntu默认目录中
        self.move_xml_to_dir(xml_name)
        print("=========== Done!!! ============")


def main():
    wallpaper_switcher = WallpaperSwitcher()
    wallpaper_switcher.run()

if __name__ == '__main__':
    main()
